# -*- coding: UTF-8 -*-
import json
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from Code.Utils.sc_func import Common
from Code.Model.sc_global import Global
from Code.Model.Data.sc_data import PlotDataError


class PlotHandler:

    @classmethod
    def csv_to_picture(cls, csv_path, pic_path, width, height, dpi, title, label, scale):
        try:
            plt.switch_backend('agg')
            plt.rcParams['font.sans-serif'] = ['SimHei']   # 用来正常显示中文标签
            plt.rcParams['axes.unicode_minus'] = False
            data = pd.read_csv(csv_path, parse_dates=True, index_col=0)
            data.plot(title=title, grid=True, style='-', figsize=(width/dpi, height/dpi))
            plt.xlabel('')
            plt.ylabel(label)
            if scale:
                plt.ylim(tuple(scale))  # 指定y轴范围
                plt.yticks(np.linspace(scale[0], scale[1], 11))  # 只显示10个刻度
            plt.savefig(pic_path, dpi=dpi)
            plt.cla()
            plt.close("all")
        except Exception as e:
            raise PlotDataError(str(e))

    @classmethod
    def make_picture(cls, data):
        ip, csv_path, params = data
        pic_path = '{}\\{}'.format(cls.get_plot_image_path(ip), Common.basename(csv_path).replace('.csv', '.png'))
        try:
            if isinstance(params, str):
                params = json.loads(params)
            width = params['width']
            height = params['height']
            dpi = params['dpi']
            title = params['title']
            label = params['label']
            scale = params['scale']
        except:
            width, height, dpi, title, label, scale = 800, 300, 80, '', '', None
        cls.csv_to_picture(csv_path, pic_path, width, height, dpi, title, label, scale)

    @classmethod
    def get_plot_image_path(cls, ip):
        path = '%s\\%s\\PLOTS' % (Global.G_PID_DIR, ip)
        if not Common.is_dir(path):
            Common.mkdir(path)
        return path

    @classmethod
    def query_plot_image_data(cls, args):
        ip, value = args
        name = Common.basename(value).replace('.csv', '.png')
        path = '{}\\{}'.format(cls.get_plot_image_path(ip), name)
        if not Common.is_file(path):
            return None
        return path

    @classmethod
    def close(cls, data=None):
        plt.close('all')

